<script setup lang="ts">
import { useRoute,useRouter } from 'vue-router'
import {ref,onMounted,nextTick,watch} from '#imports'
import {getArticleDetail} from '@/request/articles'
import { LoadingOutlined } from '@ant-design/icons-vue';
import { h } from 'vue';
import moment from 'moment'
// import { definePageMeta } from 'nuxt/dist/pages/runtime';
// 自定义加载动画
const indicator = h(LoadingOutlined, {
  style: {
    fontSize: '24px',
    textAlign: 'center',
    color: '#1890ff',
  },
  spin: true,
});
let route = useRoute();
let router = useRouter()
console.log('userRoute',route.params);
let text = ref<string>('')
let isLoadingArticleInfo = ref<boolean>(false) // 是否正在 loading文章详情
let articleInfo = ref({})

// 获取当前文章的详情
async function getArticleInfo (){
    // 获取文章详情
    isLoadingArticleInfo.value = true
    let a = await getArticleDetail(route.params.articleId)
    text.value = a.articleInfo.articleContent
    articleInfo.value = a.articleInfo
    console.log('获取到的文章内容',a);
    articleInfo.value.publicTime = moment(articleInfo.value.publicTime).format('YYYY-MM-DD')
    useSeoMeta({
        title: articleInfo.value.articleTitle,
        ogTitle: articleInfo.value.articleTitle,
        description: articleInfo.value.articleTitle,
        ogDescription: articleInfo.value.articleTitle,
    })
}
getArticleInfo()

/* 根据文章内容形成文档目录树 */
let preview = ref(null)
function getArticleTree (){
    let tree = [] // 最终目录树
    const anchors = preview.value.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
    const titles = Array.from(anchors).filter(title => !!title.innerText.trim())
    if(!titles.length){
        return []
    }

    const hTags = Array.from(new Set(titles.map(title => title.tagName))).sort()
    tree = titles.map((el:HTMLElement) => {
        let obj = {lineIndex:'',title:'',indent:''}
        obj.lineIndex = el.getAttribute('data-v-md-line'),
        obj.title = el.innerText,
        obj.indent = hTags.indexOf(el.tagName)
        return obj
    })
    
    return tree
}

interface ArticleMenuItem {
    lineIndex:string,
    title:string,
    indent:number
}

// 文章目录
let articleMenu = ref<ArticleMenuItem[]>([])
onMounted(() => {
    // 获取文章详情
   articleMenu.value = getArticleTree()
   activeLineIndex.value = articleMenu.value.length > 0 ? articleMenu.value[0].lineIndex : ''
   nextTick(() => {
    isLoadingArticleInfo.value = false
   })
})

// 跳转到对应的锚点
let activeLineIndex = ref<string>('') //激活的锚点
let isToggle = ref<boolean>(false) // 是否展开目录
let articleMenuBox = ref<HTMLElement>() // 目录盒子
let LxscrollTo = (lineIndex:string) => {
    // 给对应的文章目录item添加激活状态
    const item = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`)
    activeLineIndex.value = lineIndex
    // item.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"})
    preview.value.scrollToTarget({
        target: item,
        scrollContainer: window,
        top: 107,
    })
    nextTick(() => {
        let right_item = articleMenuBox.value?.querySelector(`[data-index="${lineIndex}"]`)
            if (right_item) {
                let y = (right_item.offsetTop - 43 - 25) / 2
                articleMenuBox.value.scrollTo({
                    top: y,
                    behavior: 'smooth'
                })
            }
    })
}


/* 收起目录 */
let toggleMenuEvent = () => {
    isToggle.value = !isToggle.value
}


let toHome = () => {
    router.push('/')
}


</script>

<template>
    <div class="lx-detail-page">
        <div class="article-info">
            <AppMainCenter>
                <template #lxMainleft>
                    <!-- 侧边栏点赞 -->
                    <div class="lx-detail-page-aside">
                        <div class="lx-detail-page-aside-item cover">
                            <img class="user-avatar-cover" src="https://ts1.cn.mm.bing.net/th?id=OIP-C._YFRagbOM8FbGUSUJy-m6QAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2" alt="" srcset="">
                        </div>
                        <div @click="toHome" class="lx-detail-page-aside-item">
                            点赞
                        </div>
                        <div class="lx-detail-page-aside-item">投币</div>
                        <div class="lx-detail-page-aside-item">123</div>
                    </div>
                    <div class="left-article-info">
                        <div class="article-top-description">
                            <h1>{{ articleInfo.articleTitle }}</h1>
                            <div class="article-author-info">
                                <p class="author">{{ articleInfo.userParty }}</p>
                                <p class="public-time">{{ articleInfo.publicTime }}</p>
                                <p class="view-count">{{  articleInfo.viewsCount ? '阅读量' + articleInfo.viewsCount : '' }}</p>
                                <p class="like-count">{{  articleInfo.likeCount ? '点赞量' + articleInfo.likeCount : '' }}</p>
                            </div>
                        </div>
                        <v-md-preview 
                            ref="preview"
                            :text="text">
                        </v-md-preview>      
                    </div>
                </template>
                <template #lxMainright>
                    <div class="right-article-info">
                        <div class="menu-title">
                            <h3>目录</h3>
                            <h5 @click="toggleMenuEvent">{{ isToggle ? '展开' : '收起' }}</h5>
                        </div>
                        <div>
                    </div>
                        <!-- <ClientOnly> -->
                            <!-- <a-spin v-if="isLoadingArticleInfo" :indicator="indicator" /> -->
                            <a-skeleton active  v-if="isLoadingArticleInfo"/>
                            <div v-else class="article-menu-box scroll-bar" ref="articleMenuBox"  :class="[isToggle ? 'is-close' : '']">
                                <div class="article-menu" :data-index="anchor.lineIndex" v-for="(anchor,index) in articleMenu" :key="anchor.lineIndex">
                                    <div class="article-menu-item" :class="[anchor.lineIndex == activeLineIndex ? 'active-menu' : '']" :style="{paddingLeft:`${anchor.indent * 1.5}rem`}" @click="LxscrollTo(anchor.lineIndex)">{{ anchor.title }}</div>
                                </div>
                            </div>
                        <!-- </ClientOnly> -->
                    </div>
                </template>
            </AppMainCenter>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.lx-detail-page {
    .article-top-cover {
        width: 100%;
        height: 35vh;
        background-size: 100%;
        background-position: 50% center;
        background-repeat: no-repeat;
        overflow: hidden;
        .article-cover {
            width: 100%;
            height: 100%;
            object-fit: contain;
            backdrop-filter: blur(120px);
        }
    }
    .article-info {
        margin: var(--lx-margin-5) auto;
        margin-bottom: 0px;
        min-height: 100vh;
        .left-article-info {
            padding: 1rem 1.667rem;
            background-color: var(--lx-page-bg-color);
            .article-top-description {
                margin-bottom: 2.667rem;
            }
            h1 {
                margin-bottom: 1rem;
            }
            .article-author-info {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                p {
                    margin-right: 1rem;
                    font-size: 13px;
                    color: var(--lx-font-3);
                    &:last-child {
                        margin-right: 0px;
                    }
                }
                .author {
                    color: var(--lx-font-2);
                }
            }
        }
    }
    .lx-detail-page-aside {
        position: fixed;
        top: 140px;
        margin-left: -5rem;
        width: 4rem;
        min-height: 200px;
        // background-color: var(--lx-font-2);
        .lx-detail-page-aside-item {
            cursor: pointer;
            width: 3rem;
            height: 3rem;
            background-color: var(--lx-page-bg-color);
            border-radius: 50%;
            box-shadow: 0 2px 4px 0 rgba(50,50,50,.04);
            text-align: center;
            line-height: 3rem;
            color: var(--lx-font-3);
            margin: 0 auto;
            margin-bottom: 1rem;
            transition: .3s all;
            &:hover {
                color: var(--lx-font-0);
                box-shadow: 0 2px 4px 0 rgba(50, 50, 50, 0.113);
            }
            .user-avatar-cover {
                display: block;
                position: relative;
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 100%;
            }
        }
        .cover {
            position: relative;
                &::after {
                    content: "关注";
                    line-height: 16px;
                    width: max-content;
                    font-size: 12px;
                    position: absolute;
                    padding: 0px var(--lx-padding-1);
                    bottom: -2px;
                    left: 50%;
                    transform: translateX(-50%);
                    border-radius: var(--radius-10);
                    background-color: var(--lx-primary-color);
                    color: var(--lx-page-color);
                }
            }
    }
    .right-article-info {
        position: sticky;
        transition: .3s all;
        top: calc(var(--lx-margin-5) + 50px);
        background-color: var(--lx-page-bg-color);
        .menu-title {
            position: sticky;
            top: 0;
            left: 0;
            display: flex;
            z-index: 22;
            align-items: center;
            justify-content: space-between;
            padding: var(--lx-padding-2) var(--lx-padding-3);
            background-color: var(--lx-page-bg-color);
            // margin: 0px var(--lx-margin-2);
            border-bottom: 1px solid var(--lx-gray-1);
            h3 {
                color: var(--lx-font-2);
            }
            h5 {
                color: var(--lx-font-3);
                cursor: pointer;
            }
        }
        .article-menu-box {
            max-height: 390px;
            overflow-y: auto;
            transition: max-height .5s;
        }
        .article-menu {
            transition: .3s all;
            position: relative;
            box-sizing: border-box;
            padding: var(--lx-padding-2) var(--lx-padding-3);
            width: 100%;
            .article-menu-item {
                cursor: pointer;
                width: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                color: var(--lx-font-2);
                &:hover {
                    color: var(--lx-primary-color);
                }
            }
            .active-menu {
                color: var(--lx-primary-color);
                &::after {
                    content: "";
                    transition: .3s all;
                    position: absolute;
                    left: 0px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 3px;
                    height: 20px;
                    border-radius: var(--radius-5);
                    background-color: var(--lx-primary-color);
                }
            }
        }
    }
    .is-close {
        max-height: 0px !important;
        transition:max-height .5s;
        overflow: hidden;
    }
}


</style>